package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.settings.service.impl.UserServiceImpl;
import com.bjpowernode.crm.utils.DateTimeUtil;
import com.bjpowernode.crm.utils.PrintJson;
import com.bjpowernode.crm.utils.ServiceFactory;
import com.bjpowernode.crm.utils.UUIDUtil;
import com.bjpowernode.crm.vo.PaginationVO;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.domain.Tran;
import com.bjpowernode.crm.workbench.domain.TranHistory;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.bjpowernode.crm.workbench.service.CustomerService;
import com.bjpowernode.crm.workbench.service.TranService;
import com.bjpowernode.crm.workbench.service.impl.ActivityServiceImpl;
import com.bjpowernode.crm.workbench.service.impl.CustomerServiceImpl;
import com.bjpowernode.crm.workbench.service.impl.TranServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: MyCRM
 * @description:
 * @author: 玉树临风的寒
 * @create: 2020-12-14 14:37:24
 **/
public class TranController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入交易控制器");

        String path = req.getServletPath();

        if ("/workbench/transaction/add.do".equals(path)) {

            add(req, resp);

        } else if ("/workbench/transaction/getCustomerName.do".equals(path)) {

            getCustomerName(req, resp);

        }else if ("/workbench/transaction/save.do".equals(path)) {

            save(req, resp);

        }else if ("/workbench/transaction/detail.do".equals(path)) {

            detail(req, resp);

        }else if ("/workbench/transaction/pageList.do".equals(path)) {

            pageList(req, resp);

        }else if ("/workbench/transaction/getHistoryListByTranId.do".equals(path)) {

            getHistoryListByTranId(req, resp);

        }else if ("/workbench/transaction/changeStage.do".equals(path)) {

            changeStage(req, resp);

        }else if ("/workbench/transaction/getCharts.do".equals(path)) {

            getCharts(req, resp);

        }
    }

    private void getCharts(HttpServletRequest req, HttpServletResponse resp) {

        System.out.println("取得交易阶段数量统计图表");

        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());
        /*
          为我们返回
          total
          names
          dataList

          通过map打包以上两项 返回
         */

        Map<String,Object> map=ts.getCharts();
        PrintJson.printJsonObj(resp,map);


    }

    private void changeStage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("执行改变阶段的操作");

        String id = req.getParameter("id");
        String stage = req.getParameter("stage");
        String money = req.getParameter("money");
        String expectedDate = req.getParameter("expectedDate");
        String editTime= DateTimeUtil.getSysTime();
        String editBy=((User)req.getSession().getAttribute("user")).getName();

        Tran t = new Tran();
        t.setId(id);
        t.setMoney(money);
        t.setStage(stage);
        t.setExpectedDate(expectedDate);
        t.setEditBy(editBy);
        t.setEditTime(editTime);

        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());

        boolean flag=ts.changeStage(t);

        Map<String,String> pMap=(Map<String,String>)this.getServletContext().getAttribute("pMap");
        t.setPossibility(pMap.get(stage));

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("success",flag);
        map.put("t",t);
        PrintJson.printJsonObj(resp,map);



    }

    private void getHistoryListByTranId(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("根据交易id 取得相应的历史列表");

        String tranId = req.getParameter("tranId");
        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());
        List<TranHistory> thList=ts.getHistoryListByTranId(tranId);

        //阶段和可能性之间的关系
        Map<String,String> pMap=(Map<String,String>)this.getServletContext().getAttribute("pMap");

        //将交易历史列表遍历
        for (TranHistory th: thList){

            //根据每一条交易历史取出每一个阶段
            String stage = th.getStage();
            String possibility =pMap.get(stage);
            th.setPossibility(possibility);
        }


        PrintJson.printJsonObj(resp,thList);

    }

    private void pageList(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("进入我写的分页操作");

        String pageNoStr = req.getParameter("pageNo");
        int pageNo = Integer.valueOf(pageNoStr);
        //每页展现的记录数
        String pageSizeStr = req.getParameter("pageSize");
        int pageSize = Integer.valueOf(pageSizeStr);
        //计算出略过的记录数
        int skipCount = (pageNo-1)*pageSize;
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("skipCount",skipCount);
        map.put("pageSize",pageSize);
        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());
        PaginationVO<Tran> vo=ts.pageList(map);
        PrintJson.printJsonObj(resp, vo);

    }

    private void detail(HttpServletRequest req, HttpServletResponse resp)     throws ServletException, IOException
    {

        System.out.println("跳转到详细信息页");
        String id  =req.getParameter("id");

        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());
        Tran t=ts.detail(id);

        //处理可能性
        /*
         阶段
         阶段和可能性之间的对应关系 pMap
         */
        String stage = t.getStage();

        //获取application 也可以使用 req.getServletContext()
       Map<String,String> pMap=(Map<String,String>)this.getServletContext().getAttribute("pMap");
       String possibility = pMap.get(stage);

       /*
           t

           vo
                private Tran t
                private String XXX...
        */

        t.setPossibility(possibility);

        req.setAttribute("t",t);
        req.getRequestDispatcher("/workbench/transaction/detail.jsp").forward(req,resp);

    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        System.out.println("执行添加交易的操作");

        String id= UUIDUtil.getUUID();
        String owner= req.getParameter("owner");
        String money= req.getParameter("money");
        String name= req.getParameter("name");
        String expectedDate= req.getParameter("expectedDate");
        String customerName= req.getParameter("customerName");//此处暂时只有客户的名称，还没有id
        String stage= req.getParameter("stage");
        String type= req.getParameter("type");
        String source= req.getParameter("source");
        String activityId= req.getParameter("activityId");
        String contactsId= req.getParameter("contactsId");
        String createTime= DateTimeUtil.getSysTime();
        String createBy=((User)req.getSession().getAttribute("user")).getName();
        String description= req.getParameter("description");
        String contactSummary= req.getParameter("contactSummary");
        String nextContactTime= req.getParameter("nextContactTime");

        Tran t =new Tran();
        t.setContactSummary(contactSummary);
        t.setDescription(description);
        t.setNextContactTime(nextContactTime);
        t.setOwner(owner);
        t.setType(type);
        t.setSource(source);
        t.setStage(stage);
        t.setActivityId(activityId);
        t.setContactsId(contactsId);
        t.setCreateTime(createTime);
        t.setCreateBy(createBy);
        t.setId(id);
        t.setName(name);
        t.setMoney(money);
        t.setExpectedDate(expectedDate);

        TranService ts= (TranService) ServiceFactory.getService(new TranServiceImpl());
        boolean flag=ts.save(t,customerName);

        if (flag){

            //如果添加交易成功，跳转到列表页
            resp.sendRedirect(req.getContextPath()+"/workbench/transaction/index.jsp");
        }

    }

    private void getCustomerName(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("取得 客户名称列表（按照客户名称进行模糊查询）");

        String name = req.getParameter("name");

        CustomerService cs = (CustomerService) ServiceFactory.getService(new CustomerServiceImpl());

        List<String> sList = cs.getCustomerName(name);

        PrintJson.printJsonObj(resp, sList);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("进入到跳转到交易添加页的操作");
        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());
        List<User> uList = us.getUserList();

        req.setAttribute("uList",uList);
        req.getRequestDispatcher("/workbench/transaction/save.jsp").forward(req,resp);

    }

}


